<template>
<el-drawer title="设置条件" :visible.sync="drawVisible" custom-class="drawer-addtional" :before-close="closeDrawer">
    <el-form :model="node" :rules="nodeRules" ref="nodeForm" label-width="5rem" label-position="left" class="form">
        <el-form-item label="条件名称" prop="title">
            <el-input v-model="node.title"></el-input>
        </el-form-item>
        <div class="condition-groups">
            <div class="condition-group" v-for="(item1, index1) in conditionGroups" :key="index1">
                <div class="condition-group-item" v-for="(item2, index2) in item1" :key="index2">
                    <el-form-item :label="item2.title">
                        <template v-if="item2.value.length == 0">
                            <div style="display: flex; align-items: center">
                                <div class="condition-value-box" @click="selectConditionValue(item2, index1, index2)">
                                    请选择{{ item2.title }}
                                </div>
                                <i class="el-icon-delete" @click="removeConditionItem(index1, index2)"></i>
                            </div>
                        </template>
                        <template v-else>
                            <div style="display: flex; align-items: center">
                                <div class="condition-value-box" @click="selectConditionValue(item2, index1, index2)">
                                    <el-tag v-for="(tag, tagIndex) in item2.value" :key="tag" closable @close="removeTag(item2.value, tagIndex)">
                                        {{ getTagTitle(tag, item2.id) }}
                                    </el-tag>
                                </div>
                                <i class="el-icon-delete" @click="removeConditionItem(index1, index2)"></i>
                            </div>
                        </template>
                    </el-form-item>
                </div>
                <el-form-item v-if="item1.length > 0">
                    <el-button @click="updateConditionGroup(item1, index1)">添加条件+</el-button>
                    <el-button @click="removeConditionGroup(index1)" type="danger">删除条件组<i class="el-icon-delete"></i></el-button>
                </el-form-item>
            </div>
        </div>
        <el-form-item>
            <el-button @click="appendConditionGroup">添加条件组+</el-button>
        </el-form-item>

        <div class="el-form-item-bottom">
            <el-button type="primary" @click="submitForm('nodeForm')">保存</el-button>
            <el-button @click="resetForm('nodeForm')">重置</el-button>
        </div>
    </el-form>

    <!-- 选择条件 -->
    <el-dialog title="选择条件" :visible.sync="conditionDialogVisible" width="30%" append-to-body :before-close="closeConditionDialog">
        <span>请选择用来区分审批流程的条件字段 ，已选{{ selectedConditionMap.length }}个</span>
        <div class="condition-group-box">
            <el-checkbox-group v-model="selectedConditionMap">
                <template v-for="(item, index) in conditionMap">
                    <el-checkbox el-checkbox :label="index" :key="index">{{ item }}</el-checkbox>
                </template>
            </el-checkbox-group>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeConditionDialog">取 消</el-button>
            <el-button type="primary" @click="confirmConditionDialog">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 绑定条件的值 -->
    <el-dialog :title="transferTitle" :visible.sync="transferDialogVisible" append-to-body>
        <div style="text-align: center">
            <el-transfer class="transfer" v-model="transferValue" filterable :titles="['选择', '已选']" :button-texts="['到左边', '到右边']" :format="{
                        noChecked: '${total}',
                        hasChecked: '${checked}/${total}'
                    }" @change="handleChange" :data="transferData">
                <span slot-scope="{ option }">{{ option.label }}</span>
            </el-transfer>
        </div>
    </el-dialog>
</el-drawer>
</template>

<script>
import {
    getAllUserApi
} from "@/api/ucenter/user";

import {
    getPickerApi,
    initPickerApi
} from "@/api/system/dictionary/dictionary";

import {
    getAllDepartmentApi
} from "@/api/ucenter/department"

export default {
    name: 'selectCondition',
    data() {
        return {
            drawVisible: false,
            conditionMap: {
                user: '提交人',
                role: '角色',
                category_id: '产品类型',
                cooperation_mode: '合作模式',
                hotel: '酒店',
                department: '部门',
            },
            conditionGroups: [], // 已添加的条件组
            appendType: 1, // 1 追加条件; 2追加条件组
            selectedConditionMap: [], // 存的是conditionMap中的索引
            targetConditionGroupindex: 0, // 追加条件时conditionGroup在conditionGroups中的索引
            conditionDialogVisible: false,
            currentConditionIndex: [0, 0],

            score: '',
            transferTitle: '',
            transferDialogVisible: false,
            transferData: [],
            transferValue: [],

            userList: [],
            roleList: [],
            categoryList: [],
            cooperateModeList: [],
            hotelList: [],
            departmentList: [],

            node: {
                data: {
                    condition: []
                },
                title: ''
            },
            nodeRules: {
                title: [{
                    required: true,
                    message: '请输入条件名称',
                    trigger: 'blur'
                }]
            }
        };
    },
    created() {
        this.getUserList();
        this.initPicker();
        this.getDepartmentList();
        this.getDictionaryList();
    },
    methods: {
        initPicker() {
            initPickerApi().then(res => {
                this.categoryList = res.data.category;
                this.hotelList = res.data.store;
            })
        },
        getDictionaryList() {
            getPickerApi({
                type: 'cooperation'
            }).then(res => {
                this.cooperateModeList = res.data.list;
            })
        },
        getDepartmentList() {
            getAllDepartmentApi().then(res => {
                this.departmentList = res.data.list;
            })
        },
        getUserList() {
            getAllUserApi().then((res) => {
                this.userList = res.data.userList;
                this.roleList = res.data.roleList;
            });
        },
        handleChange(value, direction, movedKeys) {
            let index = this.currentConditionIndex;
            let condition = this.conditionGroups[index[0]][index[1]];
            if (direction == 'right') {
                movedKeys.forEach((item) => {
                    condition.value.push(item);
                });
            } else {}

            this.conditionGroups[index[0]][index[1]] = condition;
        },

        showDrawer(node) {
            this.drawVisible = true;
            if (Object.keys(node.data).length) {
                this.conditionGroups = node.data.condition;
            }
            this.node = node;
        },

        closeDrawer() {
            this.drawVisible = false;
            this.conditionGroups = [];
            this.node = {
                title: ''
            };
            this.transferData = [];
            this.transferValue = [];
        },

        // 指定条件组，更新条件
        updateConditionGroup(currentConditionGroup, targetConditionGroupindex) {
            // 获取当前条件组中的的id也就是对应的conditionMap值
            this.targetConditionGroupindex = targetConditionGroupindex;
            let selectedConditionMap = [];
            currentConditionGroup.forEach((item) => {
                selectedConditionMap.push(item.id);
            });
            this.appendType = 1;
            // 合并当前
            this.selectedConditionMap = selectedConditionMap;
            this.conditionDialogVisible = true;
        },

        // 追加条件组
        appendConditionGroup() {
            this.appendType = 2;
            this.conditionDialogVisible = true;
        },

        // 删除条件
        removeConditionItem(parentIndex, itemIndex) {
            this.conditionGroups[parentIndex].splice(itemIndex, 1);
            if (this.conditionGroups[parentIndex].length == 0) {
                this.removeConditionGroup(parentIndex);
            }
        },

        // 删除条件组
        removeConditionGroup(index) {
            this.conditionGroups.splice(index, 1);
        },

        // 确认已选条件组
        confirmConditionDialog() {
            let conditionMap = this.conditionMap;
            this.conditionDialogVisible = false;
            let conditionGroups = this.conditionGroups;
            let selectedConditionMap = this.selectedConditionMap;
            if (selectedConditionMap.length > 0) {
                // 重组条件组中的数据格式
                let currentConditionGroup = [];
                for (let i in selectedConditionMap) {
                    let index = selectedConditionMap[i];
                    let item = {
                        title: conditionMap[index],
                        id: index,
                        value: []
                    };
                    currentConditionGroup.push(item);
                }

                if (this.appendType == 1) {
                    // 更新指定条件组条件
                    let targetConditionGroupindex = this.targetConditionGroupindex;
                    conditionGroups[targetConditionGroupindex] = currentConditionGroup;
                } else {
                    // 追加条件组
                    conditionGroups.push(currentConditionGroup);
                }
                this.conditionGroups = conditionGroups;
                this.selectedConditionMap = [];
            }
        },

        // 关闭选择条件dialog
        closeConditionDialog() {
            this.selectedConditionMap = [];
            this.conditionDialogVisible = false;
        },

        // 设置条件的值
        selectConditionValue(condition, index1, index2) {
            // 重新初始化transfer 已选的值
            this.currentConditionIndex = [index1, index2];
            this.transferValue = condition.value;
            let transferData = [];
            switch (condition.id) {
                case 'user':
                    this.transferTitle = '请选择员工';
                    let userList = this.userList;
                    userList.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.realname
                        });
                    });
                    break;

                case 'role':
                    this.transferTitle = '请选择角色';
                    let roleList = this.roleList;
                    roleList.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.title
                        });
                    });
                    break;

                case 'department':
                    this.transferTitle = '请选择部门';
                    let departmentList = this.departmentList;
                    departmentList.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.title
                        });
                    });
                    break;

                case 'plan_department':
                    this.transferTitle = '请选择策划部门';
                    let departmentList2 = this.departmentList;
                    departmentList2.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.title
                        });
                    });
                    break;

                case 'category_id':
                    this.transferTitle = '请选择产品类型';
                    let categoryList = this.categoryList;
                    categoryList.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.title
                        });
                    });
                    break;

                case 'cooperation_mode':
                    this.transferTitle = '请选择合作模式';
                    let cooperateModeList = this.cooperateModeList;
                    cooperateModeList.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.title
                        });
                    });
                    break;

                case 'hotel':
                    this.transferTitle = '请选择酒店';
                    let hotelList = this.hotelList;
                    hotelList.forEach((item) => {
                        transferData.push({
                            key: item.id,
                            label: item.title
                        });
                    });
                    break;
            }

            this.transferData = transferData;
            this.transferDialogVisible = true;
        },

        getTagTitle(id, type) {
            let title = '';
            switch (type) {
                case 'user':
                    let userList = this.userList;
                    userList.forEach((item) => {
                        if (item.id == id) {
                            title = item.realname;
                        }
                    });
                    break;

                case 'role':
                    let roleList = this.roleList;
                    roleList.forEach((item) => {
                        if (item.id == id) {
                            title = item.title;
                        }
                    });
                    break;

                case 'department':
                    let departmentList = this.departmentList;
                    departmentList.forEach((item) => {
                        if (item.id == id) {
                            title = item.title;
                        }
                    });
                    break;

                case 'plan_department':
                    let departmentList2 = this.departmentList;
                    departmentList2.forEach((item) => {
                        if (item.id == id) {
                            title = item.title;
                        }
                    });
                    break;

                case 'category_id':
                    let categoryList = this.categoryList;
                    categoryList.forEach((item) => {
                        if (item.id == id) {
                            title = item.title;
                        }
                    });
                    break;

                case 'cooperation_mode':
                    let cooperateModeList = this.cooperateModeList;
                    cooperateModeList.forEach((item) => {
                        if (item.id == id) {
                            title = item.title;
                        }
                    });
                    break;

                case 'hotel':
                    let hotelList = this.hotelList;
                    hotelList.forEach((item) => {
                        if (item.id == id) {
                            title = item.title;
                        }
                    });
                    break;
            }
            return title;
        },

        removeTag(item, index) {
            item.splice(index, 1);
            this.$forceUpdate();
        },

        submitForm(formName) {
            let node = this.node;
            let conditionGroups = this.conditionGroups;
            let condition = [];
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    conditionGroups.forEach((conditionItem) => {
                        conditionItem.forEach((itemContent) => {
                            if (itemContent.id == 'score') {
                                condition.push(itemContent.title, this.score);
                                itemContent.value = this.score;
                            } else {
                                condition.push(itemContent.title);
                                itemContent.value.forEach((value) => {
                                    condition.push(this.getTagTitle(value, itemContent.id));
                                });
                            }
                        });
                    });
                    node.data.condition = conditionGroups;
                    node.content = condition.toString();
                    this.$emit('nodeChange', node);
                    this.closeDrawer();
                } else {
                    return false;
                }
            });
        },
        resetForm(formName) {
            if (this.$refs[formName] != undefined) {
                this.$refs[formName].resetFields();
            } else {
                this.$nextTick(function () {
                    this.$refs[formName].resetFields();
                });
            }
        }
    }
};
</script>

<style lang="less" scoped>
.drawer-addtional {
    overflow: auto;
    padding-bottom: 60px;

    .form {
        position: relative;
        padding: 0 24px;
        height: 100%;
        margin-bottom: 57px;

        .condition-groups {
            border-top: 1px solid #dedede;
            margin-bottom: 1rem;

            .condition-group {
                margin: 1rem 0 1rem;
                border-bottom: 1px solid #dedede;
            }
        }

        .el-form-item-bottom {
            position: fixed;
            width: 30%;
            bottom: 0;
            right: 0;
            padding: 12px;
            border-top: 1px solid #dedede;
            background: #fff;
            text-align: center;
        }
    }
}

.condition-group-box {
    margin-top: 10px;
}

.transfer {
    text-align: left;
    display: inline-block;
}

.condition-value-box {
    margin-right: 10px;
    width: 90%;
    cursor: pointer;
    border: 1px solid #dedede;
    padding: 2px 5px;

    .el-tag {
        margin-right: 5px;
    }
}

.condition-value-box.no-border {
    padding: 0;
    border: none;
}
</style>
